package com.freesun.shop.service.imp;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.domin.ProdSolr;
import com.freesun.shop.entity.Prod;
import com.freesun.shop.entity.ProdComm;
import com.freesun.shop.entity.ProdTagReference;
import com.freesun.shop.entity.Sku;
import com.freesun.shop.mapper.ProdCommMapper;
import com.freesun.shop.mapper.ProdMapper;
import com.freesun.shop.mapper.ProdTagReferenceMapper;
import com.freesun.shop.mapper.SkuMapper;
import com.freesun.shop.service.ProdService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService {

    private static Logger log= LoggerFactory.getLogger(ProdServiceImpl.class);

    @Autowired
    private ProdTagReferenceMapper prodTagReferenceMapper;

    @Autowired
    private ProdCommMapper prodCommMapper;

    @Autowired
    private SkuMapper skuMapper;


    @Override
    public IPage<Prod> findByPage(Prod prod, Page<Prod> page) {
        log.info("分页查询商品,当前页:{},每页显示大小:{}",page.getCurrent(),page.getSize());
        IPage<Prod> iPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<Prod>()
                .select(Prod::getProdId,Prod::getOriPrice,Prod::getPrice,Prod::getImgs,
                        Prod::getTotalStocks,Prod::getProdName,Prod::getStatus,
                        Prod::getPic)
                .like(StringUtils.hasText(prod.getProdName()), Prod::getProdName, prod.getProdName())
                .eq(prod.getStatus() != null, Prod::getStatus, prod.getStatus())
                .ne(prod.getStatus()==null,Prod::getStatus,-1));
        return iPage;
    }

    @Override
    @Transactional
    public void bathDelete(List<Long> ids) {
        Assert.notNull(ids,"批量删除的集合不能为空");
        log.info("要批量删除的集合为,{}",ids);
        Prod prod=new Prod();
        prod.setStatus(-1);
        this.baseMapper.update(prod,new LambdaQueryWrapper<Prod>()
                .in(Prod::getProdId,ids));
        Sku sku = new Sku();
        sku.setIsDelete(1);
        skuMapper.update(sku,new LambdaQueryWrapper<Sku>().in(Sku::getProdId,ids));
    }

    @Override
    @Transactional
    public boolean save(Prod entity) {
        Assert.notNull(entity,"新增的商品不能为Null");
        if(
            !StringUtils.hasText(entity.getProdName()) ||
                     entity.getPrice()==null||
                     entity.getOriPrice()==null||
                     !StringUtils.hasText(entity.getPic())

        ){
            throw new RuntimeException("商品的参数格式错误");
        }
        entity.setCreateTime(LocalDateTime.now());
       Prod.DeliveryModeVo deliveryModeVo = entity.getDeliveryModeVo();
        entity.setDeliveryMode(JSONUtil.toJsonStr(deliveryModeVo));
        boolean isOK = super.save(entity);
        //商品的标签
        List<Object> tagList = entity.getTagList();
        for (Object tagObjId : tagList) {
            ProdTagReference prodTagReference = new ProdTagReference();
            prodTagReference.setProdId(entity.getProdId());
            prodTagReference.setTagId(Long.valueOf(tagObjId.toString()));
            prodTagReference.setCreateTime(LocalDateTime.now());
            prodTagReference.setStatus(true);
            prodTagReferenceMapper.insert(prodTagReference);
        }
        List<Sku> skuList = entity.getSkuList();
        for (Sku sku : skuList) {
            sku.setProdId(entity.getProdId());
            sku.setIsDelete(0);
            sku.setRecTime(LocalDateTime.now());
            sku.setUpdateTime(LocalDateTime.now());
            skuMapper.insert(sku);
        }
        return isOK;
    }

    @Override
    public Prod getById(Serializable id) {
        log.info("查询ID为:{}商品详情",id);
        Prod prod = super.getById(id);
        List<Object> tagIds = prodTagReferenceMapper.selectObjs(
                new LambdaQueryWrapper<ProdTagReference>()
                        .select(ProdTagReference::getTagId)
                        .eq(ProdTagReference::getProdId, id));
        prod.setTagList(tagIds);
        List<Sku> skus = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, id));
        prod.setSkuList(skus);
        return prod;
    }

    @Override
    public IPage<ProdSolr> findProdSolrPage(ProdSolr prodSolr, Page<Prod> page) {
        log.info("分页查询要导入到solr里面的数据当前页:{},每页大小：{}", page.getCurrent(), page.getSize());
        IPage<Prod> prodIPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<Prod>()
                .eq(Prod::getStatus, 1));
        List<Prod> prodList = prodIPage.getRecords();
        List<ProdSolr> prodSolrList = new ArrayList<>(prodList.size());
        prodList.forEach(prod -> {
            ProdSolr prodSolr2 = prod2ProdSolr(prod);
            prodSolrList.add(prodSolr2);
        });
        IPage<ProdSolr> prodSolrIPage = new Page<>();
        prodSolrIPage.setRecords(prodSolrList);
        prodSolrIPage.setTotal(prodIPage.getTotal());
        prodSolrIPage.setCurrent(prodIPage.getCurrent());
        prodSolrIPage.setSize(prodIPage.getSize());
        prodSolrIPage.setPages(prodIPage.getPages());
        return prodSolrIPage;
    }

    /**
     * 将prod转换为SOLR对象
     *
     * @param prod
     * @return
     */
    private static DecimalFormat NUM_FORMATE = new DecimalFormat("0.00");
    private ProdSolr prod2ProdSolr(Prod prod) {
        ProdSolr prodSolr=new ProdSolr();
        BeanUtils.copyProperties(prod,prodSolr);
        prodSolr.setId(prod.getProdId().toString());
        prodSolr.setTagList(getProdTagList(prod.getProdId()));
        prodSolr.setSoldNum(prod.getSoldNum()==null?0L:prod.getSoldNum().longValue());
        Integer praiseNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prod.getProdId())
                .eq(ProdComm::getEvaluate, 0));
        prodSolr.setPraiseNumber(praiseNumber==null?0L:praiseNumber);
        Integer totalCommentNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prod.getProdId()));
        BigDecimal bigDecimal=null;
        if (totalCommentNumber == null || totalCommentNumber == 0) {
            bigDecimal = new BigDecimal(100.00);
        }else{
            double score=((double)prodSolr.getPraiseNumber()/totalCommentNumber*100);

            bigDecimal = new BigDecimal(NUM_FORMATE.format(score));
        }
        prodSolr.setPositiveRating(bigDecimal);
        return prodSolr;
    }

    /**
     * 获取商品的标签
     * @param prodId
     * @return
     */
    private List<Long> getProdTagList(Long prodId) {
        List<Object> objects = prodTagReferenceMapper.selectObjs(
                new LambdaQueryWrapper<ProdTagReference>()
                        .select(ProdTagReference::getTagId)
                        .eq(ProdTagReference::getProdId, prodId));
        if (objects == null||objects.isEmpty()) {
            return new ArrayList<Long>(0);
        }
        List<Long> prodTags = new ArrayList<Long>(objects.size());
        objects.forEach(o -> {
            prodTags.add(Long.valueOf(o.toString()));
        });
        return prodTags;
    }

    @Override
    public Prod getSimpleProd(Long prodId) {
        return getById(prodId);
    }
}
